import localCache from "@/utils/cache";
// import { r } from "js-beautif-libs";
import { _recurseGetRoute } from './../../utils/js-beautif-libs/actions'
import { cloneDeep } from "lodash-es";
import { asyncRoutes, constantRoutes } from "@/router";

const state = {
  routes: [],
  addRoutes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  generatePlatformRoutes({ commit }) {
    return new Promise((resolve) => {
      const menusTree = localCache.getCache("userInfo").menuTree ?? [];
      const menuNames = [];
      const _recurseGetMenuName = (menusTree) => {
        menusTree.forEach((item, index) => {
          menuNames.push({ code: item.code, name: item.name, order: index });
          if (item.children?.length > 0) {
            _recurseGetMenuName(item.children);
          }
        });
        return menuNames;
      };
      _recurseGetMenuName(menusTree);
      const routers = _recurseGetRoute(cloneDeep(asyncRoutes), menuNames).sort((a, b) =>
        a.order ? a.order - b.order : -1
      );
      commit("user/SET_RELOAD_ROUTER", true, { root: true });
      commit("SET_ROUTES", routers);
      resolve(routers);
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
